package eventengine.middleware;

/**
 * <p>Title: TupleSpace</p>
 * <p>Description: TupleSpace</p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: DII - DISMI</p>
 * @author Marco Mamei
 * @version 1.0
 */

import java.util.*;

import emulator.agent.*;
import emulator.peers.*;
import emulator.utils.*;

import tuplespace.tuples.*;

public class EventServer implements EventInterface
{
 private String id;
 private ArrayList sub;

 public EventServer(String id)
 {
  this.id = id;
  sub = new ArrayList();
 }

 /*****************************************************************************/
 /*                          EVENT INTERFACE                                  */
 /*****************************************************************************/
 /* this method allows to subscribe to an event */
 public void subscribe(Tuple template, ReactiveComponent comp, String method)
 {
  sub.add(new TempCompReact(template, comp, method));
 }

 /* this method allows to unsubscribe to an event */
 public void unsubscribe(Tuple template, ReactiveComponent comp)
 {
  /* create a clone of the subscribed list to avoid concurrency problems */
  ArrayList fireSub = (ArrayList)sub.clone();

  for(int i=0;i<fireSub.size();i++)
  {
   TempCompReact tcr = (TempCompReact)fireSub.get(i);

   if(tcr.temp.match(template) && tcr.comp.equals(comp))
   {
    sub.remove(tcr);
   }
  }
 }

 /* this method allows to fire an event */
 public void generateEvent(Tuple event)
 {
  /* create a clone of the subscribed list to avoid concurrency problems */
  ArrayList fireSub = (ArrayList)sub.clone();
  
  if(id.startsWith("TOTAP3TS") || id.startsWith("TOTAP3VTS")) {
   System.out.println(id+": "+event.serialize());
  }
  
  
  for(int i=0;i<fireSub.size();i++)
  {
   TempCompReact tcr = (TempCompReact)fireSub.get(i);

   if(event.match(tcr.temp)) {
    tcr.comp.react(tcr.react,event.serialize());
   }
  }
 }

 /* this method is for debugging purposes; it allows to see the actual list of
 subscriptions */
 public void printSubscriptions()
 {
  for(int i=0;i<sub.size();i++)
  {
   TempCompReact tcr = (TempCompReact)sub.get(i);
   System.out.println(id+"  "+tcr.toString());
  }
 }
}

/******************************************************************************/
/******************************************************************************/

/* this is just a wrapper class to hold togethet all the stuff related to a
subscription */
class TempCompReact
{
 Tuple temp;
 ReactiveComponent comp;
 String react;
 public TempCompReact (Tuple template, ReactiveComponent comp, String react)
 {
  this.temp = template;
  this.comp = comp;
  this.react = react;
 }
 public String toString()
 {
  return new String("TEMP: "+temp.getContent()+" COMP: "+comp.toString()+" REACT: "+react);
 }
}